import { Pagination, PaginationProps } from 'antd';
import { FC, useEffect, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { LIST_PAGE_KEY, LIST_PAGE_SIZE_KEY, LIST_PAGE_SIZE } from '../../constants';
type PropsType = {
  total: number;
};

const ListPage: FC<PropsType> = (props: PropsType) => {
  const { total } = props;
  const [searchParams] = useSearchParams();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(1);

  useEffect(() => {
    const page = parseInt(searchParams.get(LIST_PAGE_KEY) || '') || 1;
    const pageSize = parseInt(searchParams.get(LIST_PAGE_SIZE_KEY) || '') || LIST_PAGE_SIZE;
    setCurrent(page);
    setPageSize(pageSize);
  }, [searchParams]);
  const nav = useNavigate();
  const { pathname } = useLocation();
  const onChange: PaginationProps['onChange'] = (page: number, pageSize: number) => {
    console.log('onChange', page, pageSize);
    setCurrent(page);
    setPageSize(pageSize);
    searchParams.set(LIST_PAGE_KEY, page.toString());
    searchParams.set(LIST_PAGE_SIZE_KEY, pageSize.toString());
    nav({
      pathname,
      search: searchParams.toString(),
    });
  };
  return (
    <Pagination
      current={current}
      pageSize={pageSize}
      onChange={onChange}
      defaultCurrent={1}
      total={total}
    />
  );
};

export default ListPage;
